﻿using AutoMapper;
using HandyControl.Data;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows;
using TransformerManager.Shared.Dto;
using TransformerManager.Shared.Helper.HttpParams;
using TransformerManager.WPF.Common.Http;
using TransformerManager.WPF.Common.Http.Service;
using hc = HandyControl.Controls;

namespace TransformerManager.WPF.UsersModule.ViewModels
{
    public class UsersViewModel : BindableBase, INavigationAware
    {
        private readonly IDialogService _dialogService;
        private readonly IUserInfoService _userInfoService;
        public UsersViewModel(
            IDialogService dialogService,
            IUserInfoService userInfoService)
        {
            _dialogService = dialogService;
            _userInfoService = userInfoService;

            InitCmd();
        }

        #region Command
        public DelegateCommand ResetPasswordCmd { private set; get; }

        public DelegateCommand AuthorizeAdminCmd { private set; get; }

        public DelegateCommand EditCmd { private set; get; }

        public DelegateCommand SearchCmd { private set; get; }

        public DelegateCommand<FunctionEventArgs<int>> PageUpdatedCmd { private set; get; }

        #endregion


        #region 方法的定义

        private ObservableCollection<UserBasicParams> _showUserDataList
            = new ObservableCollection<UserBasicParams>();
        public ObservableCollection<UserBasicParams> ShowUserDataList
        {
            set
            {
                _showUserDataList = value;

                RaisePropertyChanged();
            }
            get
            {
                return _showUserDataList;
            }
        }

        private UserBasicParams _selectedUser
            = new UserBasicParams();
        public UserBasicParams SelectedUser
        {
            set
            {
                _selectedUser = value;

                RaisePropertyChanged();
            }
            get
            {
                return _selectedUser;
            }
        }

        private Visibility _isShowPaginationAndDataGrid
            = Visibility.Collapsed;
        public Visibility IsShowPaginationAndDataGrid
        {
            set
            {
                _isShowPaginationAndDataGrid = value;

                RaisePropertyChanged();
            }

            get
            {
                return _isShowPaginationAndDataGrid;
            }
        }

        private int _pageIndex = 1;
        public int PageIndex
        {
            set
            {
                _pageIndex = value;

                RaisePropertyChanged();
            }
            get
            {
                return _pageIndex;
            }
        }

        private int _maxPageCount;
        public int MaxPageCount
        {
            set
            {
                _maxPageCount = value;

                RaisePropertyChanged();
            }
            get
            {
                return _maxPageCount;
            }
        }

        private int _dataCountPerPage = 15;
        public int DataCountPerPage
        {
            set
            {
                _dataCountPerPage = value;

                RaisePropertyChanged();
            }

            get
            {
                return _dataCountPerPage;
            }
        }

        private string _keywords = string.Empty;
        public string Keywords
        {
            set
            {
                _keywords = value;

                RaisePropertyChanged();
            }

            get
            {
                return _keywords;
            }
        }
        #endregion


        #region 函数的定义

        private void InitCmd()
        {
            AuthorizeAdminCmd = new DelegateCommand(async () =>
            {
                await ManageAuthorizeAdmin();
            });

            EditCmd = new DelegateCommand(() =>
            {
                EditUserInfo();
            });

            ResetPasswordCmd = new DelegateCommand(async () =>
            {
                await ResetUserPassword();
            });

            SearchCmd = new DelegateCommand(async () =>
            {
                await RetrieveUserDataList(1, _dataCountPerPage);
            });

            PageUpdatedCmd = new DelegateCommand<FunctionEventArgs<int>>(async (curPageNum) =>
            {
                await PageUpdated(curPageNum);
            });
        }

        private async Task ResetUserPassword()
        {
            // 请求重置密码
            var result = await _userInfoService.ResetUserPasswordAsync(SelectedUser.UserName);
            if (!result.Success)
            {
                hc.Growl.Error(
                        $"响应信息: {result.Message}",
                        "Notification");
                return;
            }
            hc.Growl.Success($"响应信息：{result.Message}", "Notification");
        }

        private void EditUserInfo()
        {
            var dialogParams = new DialogParameters() { { "UserInfo", _selectedUser } };

            _dialogService.ShowDialog("UserInfoDialog", dialogParams, async r =>
            {
                if (r.Result == ButtonResult.OK)
                {
                    _selectedUser = r.Parameters.GetValue<UserBasicParams>("CurrentUserInfo");

                    var result = await _userInfoService.ModifyUserInfoAsync(_selectedUser);

                    if (!result.Success)
                    {
                        hc.Growl.Error(
                                $"响应信息: {result.Message}",
                                "Notification");
                        return;
                    }
                    hc.Growl.Success($"响应信息：{result.Message}", "Notification");
                }
            });
            
        }

        private async Task ManageAuthorizeAdmin()
        {
            if (SelectedUser == null) return;

            ServiceResponse result;
            int index = ShowUserDataList.IndexOf(SelectedUser);
            // 授权或取消授权, 若本来为Admin,点击后就会取消授权,反过来一个道理
            if (SelectedUser.Roles.Contains("Admin"))
            {
                result = await _userInfoService.UnauthorizeRole(SelectedUser.UserName);
                
                if (!result.Success)
                {
                    hc.Growl.Error(
                            $"响应信息: {result.Message}",
                            "Notification");
                }
                else
                {
                    SelectedUser.Roles.Remove("Admin");
                    hc.Growl.Success($"响应信息：{result.Message}", "Notification");
                }
                
            }
            else
            {
                result = await _userInfoService.AuthorizeRole(SelectedUser.UserName);
                if (!result.Success)
                {
                    hc.Growl.Error(
                            $"响应信息: {result.Message}",
                            "Notification");
                }
                else
                {
                    SelectedUser.Roles.Add("Admin");
                    hc.Growl.Success($"响应信息：{result.Message}", "Notification");
                }
            }

            ShowUserDataList[index] = new UserBasicParams()
            {
                UserId = SelectedUser.UserId,
                UserName = SelectedUser.UserName,
                RealNameEn = SelectedUser.RealNameEn,
                RealNameCn = SelectedUser.RealNameCn,
                Department = SelectedUser.Department,
                IsLeadEngineer = SelectedUser.IsLeadEngineer,
                Roles = SelectedUser.Roles
            };
        }

        private async Task PageUpdated(FunctionEventArgs<int> curPageNum)
        {
            await RetrieveUserDataList(curPageNum.Info, _dataCountPerPage);
        }

        public async Task RetrieveUserDataList(
            int pageIndex, int pageSize)
        {
            var resultWithHeaders = await _userInfoService.GetUsersAsync(_keywords, false, pageIndex, pageSize);
            if (resultWithHeaders == null || resultWithHeaders.Data.Count == 0)
            {
                ShowUserDataList.Clear();
                IsShowPaginationAndDataGrid = _showUserDataList.Count() == 0 ? Visibility.Collapsed : Visibility.Visible;
                return;
            }

            // 从响应中获取分页信息
            var headersParams = resultWithHeaders.Headers.Where(h => h.Key == "x-pagination").FirstOrDefault();
            var paginationParams = JsonConvert.DeserializeObject<PaginationParams>(headersParams.Value.FirstOrDefault());

            // 更新界面参数
            ShowUserDataList = new ObservableCollection<UserBasicParams>(resultWithHeaders.Data);
            IsShowPaginationAndDataGrid = ShowUserDataList.Count() == 0 ? Visibility.Collapsed : Visibility.Visible;
            DataCountPerPage = paginationParams.PageSize;
            PageIndex = paginationParams.CurrentPage;
            MaxPageCount = paginationParams.TotalPages;
        }

        private async Task SetDataGridSource()
        {
            _showUserDataList.Clear();

            await RetrieveUserDataList(_pageIndex, _dataCountPerPage);
        }

        #endregion


        #region 接口的实现

        public async void OnNavigatedTo(NavigationContext navigationContext)
        {
            await SetDataGridSource();
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {

        }

        #endregion

    }
}
